package com.example.back.Controller;

import com.example.back.Annotation.UserLoginToken;
import com.example.back.Entity.Cart;
import com.example.back.Repository.CartRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 购物车模块，内部存了用户加入到购物车中的商品
 */
@RestController
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private CartRepository cartRepository;

    //加入购物车
    @UserLoginToken
    @PostMapping("")
    public boolean addNewCart(@RequestBody Cart cart) {
        //限制加入购物车，如果已经存在了就不能加入到购物车里
        List<Cart> TempCartList = cartRepository.findAllByUserId(cart.getUserId());
        for (Cart TempCartItem : TempCartList)
            if (TempCartItem.getProductId() == cart.getProductId())
                return false;

        try {
            cart.setAddDate(new Date());
            cartRepository.save(cart);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    //根据userId获取购物车中商品
    @UserLoginToken
    @GetMapping("/{userId}")
    public List<Cart> findAllByCartId(@PathVariable("userId") long userId) {
        return cartRepository.findAllByUserId(userId, Sort.by(Sort.Direction.ASC, "addDate"));
    }

    //删除购物车中的数据
    @UserLoginToken
    @DeleteMapping("/{cid}")
    public boolean deleteByCartId(@PathVariable("cid") long cid) {
        try {
            cartRepository.deleteById(cid);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
